package watcher

import (
	"github.com/shirou/gopsutil/load"
	"time"
	"watcher/client/config"
)

type LoadavgWatcher struct {
	Done     chan struct{}
	Duration time.Duration
}

func (watcher *LoadavgWatcher) Watch() <-chan *WatchData {
	dataChan := make(chan *WatchData, 10)
	go watcher.watch(dataChan, watcher.Duration)
	return dataChan
}

func (watcher *LoadavgWatcher) watch(ch chan *WatchData, duration time.Duration) {
	defer close(ch)
	ticker := time.NewTicker(duration)
	for t := range ticker.C {
		select {
		case <-watcher.Done:
			ticker.Stop()
			break
		default:
			func() {
				f, err := load.Avg()
				if err != nil {
					return
				}
				ch <- &WatchData{
					Measurement: "loadavg",
					Time:        t,
					Fields: map[string]interface{}{
						"load1":  f.Load1,
						"load5":  f.Load5,
						"load15": f.Load15,
					},
				}
			}()
		}
	}
}

func (watcher *LoadavgWatcher) Close() {
	close(watcher.Done)
}

func NewLoadavgWatcher(conf config.Conf) (*LoadavgWatcher, error) {
	return &LoadavgWatcher{
		Done:     make(chan struct{}),
		Duration: conf.Duration,
	}, nil
}

var LoadavgRegister = func(conf config.Conf) (string, Watcher, error) {
	wt, err := NewLoadavgWatcher(conf)
	return "loadavg", wt, err
}
